package com.tnl;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.log4j.Logger;


public class MD5 {
	protected static Logger logger = Logger.getLogger(MD5.class);
	
	public static String encryptByMD5(String strSrc) {
		return encrypt(strSrc, "MD5");
	}
	
	public static String encrypt(String strSrc, String encName) {
		// parameter strSrc is a string will be encrypted,
		// parameter encName is the algorithm name will be used.
		// encName dafault to "MD5"
		// 得到MessageDigest对象
		MessageDigest md = null;
		MD5 mept = new MD5();
		// 加密后的字符串
		String strDes = null;
		// 要加密的字符串字节型数组
		byte[] bt = strSrc.getBytes();
		try {
			if (encName == null || encName.equals("")) {
				encName = "MD5";
			}
			md = MessageDigest.getInstance(encName);
			md.update(bt);
			// 通过执行诸如填充之类的最终操作完成哈希计算
			strDes = mept.bytes2Hex(md.digest()); // to HexString
		} catch (NoSuchAlgorithmException e) {
			logger.error("字符串 "+strSrc+" 尝试通过["+encName+"方式] 	加密失败.");
		}
		return strDes;
	}

	// 将字节数组转换成16进制的字符串
	private String bytes2Hex(byte[] bts) {
		StringBuffer buffer = new StringBuffer("");
		String tmp = null;
		for (int i = 0; i < bts.length; i++) {
			tmp = (Integer.toHexString(bts[i] & 0xFF));
			if (tmp.length() == 1) {
				buffer.append("0");
			}
			buffer.append(tmp);
		}
		return buffer.toString();
	}

}
